<template>
    <el-form ref="ruleFormRef" style="max-width: 600px" :model="ruleForm" :rules="rules" label-width="auto"
        class="demo-ruleForm" :size="formSize" status-icon>
        <el-form-item label="账号" prop="username">
            <el-input v-model="ruleForm.username" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
            <el-input v-model="ruleForm.password" />
        </el-form-item>
        <el-form-item>
            <el-button type="primary" @click="submitForm(ruleFormRef)">
                登录
            </el-button>

        </el-form-item>
    </el-form>
</template>

<script setup>
import api from '@/api/api'
import { reactive, ref } from 'vue'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router';
const router=useRouter()
const ruleFormRef = ref()
const ruleForm = reactive({
    username: '',
    password: '',
})

const rules = reactive({
    username: [
        { required: true, message: '请输入账号', trigger: 'blur' },
        { min: 3, max: 5, message: 'Length should be 3 to 5', trigger: 'blur' },
    ],
    password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 3, max: 5, message: 'Length should be 3 to 5', trigger: 'blur' },
    ],

})
const submitForm = async (formEl) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            console.log('submit!')
            api.post('/login', ruleForm).then(res => {
                if (res.status === 200 && res.data.code === 10000) {
                    localStorage.setItem = 'accessToken', res.data.data.accessToken
                    localStorage.setItem = 'refreshToken', res.data.data.refresToken
                    localStorage.setItem('avator', res.data.data.userInfo.avator)
                    localStorage.setItem('role', res.data.data.userInfo.username)
                    ElMessage({
                        message: '登录成功',
                        type: 'success',
                    })
               router.push('/')
                }
            })
        } else {
            ElMessage({
                        message: '登录失败',
                        type: 'success',
                    })
        }
    })
}


</script>

<style lang="scss" scoped></style>